<?php
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/init.php';

/**
 *向(财务系统)fin同步仓库信息
 *@author shipanpan
 */
class SynWarehouseController extends Controller_CronJob {
	private $_domain;
	private $_authToken;
	private $_authSn;

	private $_allWarehouseDep;
	public function __construct() {
		parent::__construct();
		$this->_domain = Helper_Config::get('url', 'fin', 'url');
		$this->_authToken = Helper_Config::get('auth', 'fin', 'token');
		$this->_authSn = Helper_Config::get('auth', 'fin', 'sn');
		$this->_allWarehouseDep = $this->getWarehouseDep();
	}

	public function getWarehouseDep() {
		return $this->db->fetchAssoc('select department_sn,department_name,id from c_warehouse_dept');
	}

	public function run($pageIndex = 1) {
		$url = $this->_domain . 'inter/warehouse/get?' . 'token=' . $this->_authToken . '&sn=' . $this->_authSn;
		$perPage = 500;
		try {
			$response = Controller_Interface::post($url, ['page' => $pageIndex, 'per_page' => $perPage]);
			$warehouse = json_decode($response, true);
		} catch (Exception $e) {
			$errorMsg = "向财务系统同步仓库数据发生错误:" . $e->getMessage();
			$this->log->record($errorMsg, Log::WARN);
			die($errorMsg);
		}

		if (!$warehouse) {
			$errorMsg = "向财务系统同步仓库数据发生错误:" . json_last_error_msg();
			$this->log->record($errorMsg, Log::WARN);
			die($errorMsg);
		}

		if (!isset($warehouse['total'], $warehouse['page'], $warehouse['per_page'])) {
			$errorMsg = "财务系统返回的仓库数据异常";
			$this->log->record($errorMsg, Log::WARN);
			die($errorMsg);
		}
		if (!$warehouse['total'] || !$warehouse['page'] || !$warehouse['per_page']) {
			$errorMsg = "财务系统返回的仓库数据格式异常";
			$this->log->record($errorMsg, Log::WARN);
			die($errorMsg);
		}

		foreach ($warehouse['list'] as $_oneWarehouse) {
			$weNeedWarehouseData = [];
			$weNeedWarehouseData['warehouse_code'] = $_oneWarehouse['warehouse_sn'];
			$weNeedWarehouseData['warehouse_name'] = $_oneWarehouse['warehouse_name'];
			//$weNeedWarehouseData['is_oversea'] = $_oneWarehouse['is_overseas'];

			Model_Base::insertOrUpdate($this->writeDb, 'c_warehouse', $weNeedWarehouseData);
		}

		if ($warehouse['page'] * $warehouse['per_page'] < $warehouse['total']) {

			return $this->run(++$warehouse['page']);
		}

	}
}

$synWarehouse = new SynWarehouseController();
$synWarehouse->run();